/**  
 * @date 2023-11-24 
 * @author Zhang Yu
 */
package com.jwt.shiro.demo.config;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.jwt.shiro.demo.filter.JWTFilter;
import com.jwt.shiro.demo.shiro.CustomRealm;

import javax.servlet.Filter;



/**  
 * @description: TODO
 */
@Configuration
public class ShiroConfig {
	
	@Bean
	public ShiroFilterFactoryBean factory(SecurityManager securityManager) {
		ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
		Map<String, Filter> filterMap = new LinkedHashMap<>();
		filterMap.put("jwt", new JWTFilter());
		factoryBean.setFilters(filterMap);
		factoryBean.setSecurityManager(securityManager);
		factoryBean.setUnauthorizedUrl("/unauthorized/无权限");
		Map<String, String> filterRuleMap = new HashMap<String, String>();
		filterRuleMap.put("/**", "jwt");
		filterRuleMap.put("/unauthorized/**", "anon");
		factoryBean.setFilterChainDefinitionMap(filterRuleMap);
		return factoryBean;
	}

    @Bean
    CustomRealm customRealm() {
        return new CustomRealm();
    }
	
    /**
     * 注入 securityManager
     */
    @Bean
    public SecurityManager securityManager(CustomRealm customRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 设置自定义 realm.
        securityManager.setRealm(customRealm());
        return securityManager;
    }

}
